#pragma once
#include <iostream>
#include <pthread.h>
#include <queue>

namespace ns_thread_pool
{
    // 线程池只限制线程数，不限制任务数
    template <class T, size_t NUM = 5>
    class ThreadPool
    {
    private:
        std::queue<T> _q;
        int _num;

        pthread_mutex_t _mtx;
        pthread_cond_t _cond;

    private:
        void Lock()
        {
            pthread_mutex_lock(&_mtx);
        }

        void Unlock()
        {
            pthread_mutex_unlock(&_mtx);
        }

        void Wait()
        {
            pthread_cond_wait(&_cond, &_mtx);
        }

        void WakeUp()
        {
            pthread_cond_signal(&_cond);
        }

        bool IsEmpty()
        {
            return _q.empty();
        }

    public:
        ThreadPool()
            :_num(NUM)
        {
            pthread_mutex_init(&_mtx, nullptr);
            pthread_cond_init(&_cond, nullptr);
        }

        ~ThreadPool()
        {
            pthread_mutex_destroy(&_mtx);
            pthread_cond_destroy(&_cond);
        }

        void InitThreadPool()
        {
            pthread_t pid;
            for(int i = 0; i < _num; ++i)
            {
                pthread_create(&pid, nullptr, Rountine, (void*)this);
            }
        }

        void Pop(T* data)
        {
            *data = _q.front();
            _q.pop();
        }

        void Push(const T& data)
        {
            Lock();
            _q.push(data);
            Unlock();
            WakeUp();
        }

        static void* Rountine(void* args)
        {
            pthread_detach(pthread_self());
            ThreadPool<T>* tp = (ThreadPool<T>*)args;

            while(true)
            {
                tp->Lock();
                while(tp->IsEmpty())
                {
                    tp->Wait();
                }

                T t;
                tp->Pop(&t);
                tp->Unlock();
                t();
            }
        }
    };
}